package com.yz.xyt.service.impl;

import com.yz.xyt.domain.Menu;
import com.yz.xyt.mapper.MenuMapper;
import com.yz.xyt.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl implements IMenuService {

    @Autowired
    MenuMapper menuMapper;

    @Transactional
    @Override
    public int deleteByPrimaryKey(Integer id) {
        return 0;
    }

    @Transactional
    @Override
    public int insert(Menu record) {
        return 0;
    }

    @Transactional
    @Override
    public int insertSelective(Menu record) {
        return 0;
    }

    @Override
    public Menu selectByPrimaryKey(Integer id) {
        return null;
    }

    @Override
    public int updateByPrimaryKeySelective(Menu record) {
        return 0;
    }

    @Transactional
    @Override
    public int updateByPrimaryKey(Menu record) {
        return 0;
    }

    @Override
    public List<String> selectPermsByUserId(Long userId) {
        return menuMapper.selectPermsByUserId(userId);
    }

    @Override
    public List<Menu> selectUserMenusByUserId(Long userId) {
        return menuMapper.selectUserMenusByUserId(userId);
    }

    @Override
    public List<Menu> selectByPid(Menu menu) {
        return menuMapper.selectByPid(menu);
    }

    /**
     * 查询app菜单
     * @param userId
     * @return
     */
    @Override
    public List<Menu> selectAppMenus(Long userId){
        return menuMapper.selectAppMenus(userId);
    }

    /**
     * 递归查询菜单树
     * @param pmenu
     * @return
     */
    @Override
    public List<Menu> getMenuTree(Menu pmenu) {
        List<Menu> menuList = selectByPid(pmenu);
        if (menuList.size()>0){
            Menu menu=new Menu();
            menuList.stream().forEach(menu1 -> {
                menu.setId(menu1.getId());
                List<Menu> childList = getMenuTree(menu);
                if (childList.size() > 0){
                    menu1.setChild(childList);
                }
            });
        }
        return menuList;
    }

    /**
     * 递归构建菜单树
     * @param list
     * @param root
     * @return
     */
    @Override
    public Menu getMenuTree(List<Menu> list,Menu root){
        for (Menu node : list){
            if(root.getId().equals(node.getPid())){
                List<Menu> children;
                if (root.getChild() !=null){
                    children = root.getChild();
                }else{
                    children = new ArrayList<>();
                }
                children.add(getMenuTree(list,node));
                root.setChild(children);
            }
        }
        return root;
    }
}
